package earogya.ehr.patient_details.messages;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.TS;
import ca.uhn.hl7v2.model.v251.message.ADT_A60;
import ca.uhn.hl7v2.model.v251.segment.IAM;
import earogya.ehr.patient_details.HibernateManager;
import earogya.ehr.patient_details.PatientAllergy;

public class ADT_A60_Handler {

	private ADT_A60 adtMsg;
	private PatientAllergy pAllergy;
	HibernateManager hibernateManager=new HibernateManager();
	public ADT_A60_Handler(ADT_A60 adtMsg){
		this.adtMsg=adtMsg;
	}
	
	public String manageMessage() throws HL7Exception, IOException{
		this.updateAllergyDetails();
		String ack=adtMsg.generateACK().encode();
		return ack;
	}
	
	private void updateAllergyDetails() throws NumberFormatException, HL7Exception{
		IAM iam;
		System.out.print(adtMsg.getIAMReps());
		for(int i=0;i<adtMsg.getIAMReps();i++){
			iam=adtMsg.getIAM(i);
			pAllergy=new PatientAllergy();
			System.out.print(adtMsg.getIAM(i).getAllergenCodeMnemonicDescription().getComponent(0).toString());
			//pAllergy.setPatientId(Integer.parseInt(adtMsg.getPID().getPatientID().getComponent(0).toString()));
			pAllergy.setPatientId(Integer.parseInt(adtMsg.getPID().getPatientID().getIDNumber().getValue()));
			pAllergy.setAllergyCode(iam.getAllergenCodeMnemonicDescription().getComponent(0).toString());
			pAllergy.setSeverity(iam.getAllergySeverityCode().getComponent(0).toString());
			pAllergy.setIdentificationDate(this.tsToDate(iam.getReportedDateTime()));
			System.out.print(adtMsg.getPID().getPatientID().getComponent(0).getName());
			hibernateManager.saveObject(pAllergy);
		}
	}
	
	private Date tsToDate(TS ts) throws HL7Exception {
		// need to handle timezone
		Calendar cal = Calendar.getInstance();
		if(ts.getTime().getValue()!=null){
		String dtm = ts.getTime().getValue();
		int year = Integer.parseInt(dtm.substring(0, 4));
		int month = (dtm.length() >= 6 ? Integer.parseInt(dtm.substring(4, 6)) - 1 : 0);
		int day = (dtm.length() >= 8 ? Integer.parseInt(dtm.substring(6, 8)) : 1);
		int hour = (dtm.length() >= 10 ? Integer.parseInt(dtm.substring(8, 10)) : 0);
		int min = (dtm.length() >= 12 ? Integer.parseInt(dtm.substring(10, 12)) : 0);
		int sec = (dtm.length() >= 14 ? Integer.parseInt(dtm.substring(12, 14)) : 0);
		
		cal.set(year, month, day, hour, min, sec);
		}
		else{
			cal.set(1986, 5, 25, 22, 33, 44);
		}
		return cal.getTime();
	}
	
}
